package com.xiaoxx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaoxx.model.entity.sys.SysMsg;
import com.xiaoxx.mapper.SysMsgMapper;
import com.xiaoxx.model.vo.sys.SysMsgListVo;
import com.xiaoxx.model.vo.sys.SysMsgQuery;
import com.xiaoxx.model.vo.sys.SysMsgVo;
import com.xiaoxx.service.SysMsgService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaoxx.utils.BeanDtoVoUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 * base--sys--消息通知 服务实现类
 * </p>
 *
 * @author HX
 * @since 2023-08-03
 */
@Service
public class SysMsgServiceImpl extends ServiceImpl<SysMsgMapper, SysMsg> implements SysMsgService {

    @Override
    public IPage<SysMsgListVo> listMsg(SysMsgQuery query) {
        Page<SysMsg> page = lambdaQuery()
                .eq(SysMsg::getUserId, query.getUserId())
                .eq(query.getIsRead() != null, SysMsg::getIsRead, query.getIsRead())
                .like(StringUtils.hasLength(query.getTitile()), SysMsg::getTitile, query.getTitile())
                .orderByDesc(SysMsg::getCreateTime)
                .page(new Page<>(query.getCurrent(), query.getSize()));
        return BeanDtoVoUtil.pageVo(page, SysMsgListVo.class);
    }

    @Override
    public Boolean delRead(String userId) {
        return remove(new LambdaQueryWrapper<SysMsg>()
                .eq(SysMsg::getIsRead, 1)
                .eq(SysMsg::getUserId, userId));
    }

    @Override
    public Integer getNotReadCount(String userId) {
        return count(new LambdaQueryWrapper<SysMsg>()
                .eq(SysMsg::getIsRead, 0)
                .eq(SysMsg::getUserId, userId));

    }

    @Override
    public SysMsgVo findById(String id) {
        SysMsg sysMsg = new SysMsg();
        sysMsg.setIsRead(1);
        sysMsg.setId(id);
        updateById(sysMsg);
        return getById(id).convert(SysMsgVo.class);
    }

    @Override
    public Boolean readAll(String userId) {
        return update(new LambdaUpdateWrapper<SysMsg>()
                .set(SysMsg::getIsRead, 1)
                .eq(SysMsg::getUserId, userId)
                .eq(SysMsg::getIsRead, 0));

    }
}
